//
//  CYYChangeInfoViewController.m
//  LetsParty
//
//  Created by rimi on 15/9/16.
//  Copyright (c) 2015年 LetsPartyTeam. All rights reserved.
//

#import "CYYChangeInfoViewController.h"

@interface CYYChangeInfoViewController ()

@property (nonatomic, strong) UIScrollView * mainScrollView;//主滚动视图
@property (nonatomic, strong) UITextField * usernameTextField;//用户名
@property (nonatomic, strong) UITextField * mobilePhoneNumberTextField;//手机号
@property (nonatomic, strong) UILabel * remindLabel;
@property (nonatomic, strong) UITextField * newFirstPasswordTextField;//第一次输入的密码
@property (nonatomic, strong) UITextField * newSecondpasswordTextField;//第二次输入的密码
@property (nonatomic, strong) UIButton * okButton;//确定button
@property (nonatomic, strong) UISwitch * isChangePasswordSwitch;//是否修改密码
@property (nonatomic, strong) UIAlertController * backAlterViewController;

-(void)initializeUserInterface;

@end

@implementation CYYChangeInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeUserInterface];
    //监听键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHiden:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:UIKeyboardWillHideNotification];
    [[NSNotificationCenter defaultCenter] removeObserver:UIKeyboardWillShowNotification];
}
#pragma mark - init
-(void)initializeUserInterface{
    self.bartitleLabel.text = @"修改个人信息";
    self.baseNavigationBar.backgroundColor = [UIColor whiteColor];
    [self.leftNavButton setImage:[UIImage imageNamed:@"iconfont-zuojiantou"] forState:UIControlStateNormal];
    [self.leftNavButton addTarget:self action:@selector(respondsToLeftButton:) forControlEvents:UIControlEventTouchUpInside];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.mainScrollView];
    [self.mainScrollView addSubview:self.usernameTextField];
    [self.mainScrollView addSubview:self.mobilePhoneNumberTextField];
    [self.mainScrollView addSubview:self.remindLabel];
    [self.mainScrollView addSubview:self.newFirstPasswordTextField];
    [self.mainScrollView addSubview:self.newSecondpasswordTextField];
    [self.mainScrollView addSubview:self.okButton];
    [self.mainScrollView addSubview:self.isChangePasswordSwitch];
}

#pragma mark - private methods
- (void)respondsToLeftButton:(UIButton *)button{
    [[ControllerManager sharedManager].rootViewController popViewControllerAnimated:YES];
}

- (void)alterViewWithMessage:(NSString *)message{
    UIAlertController * alterViewController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alterViewController addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        [alterViewController dismissViewControllerAnimated:YES completion:nil];
    }]];
    [self.parentViewController presentViewController:alterViewController animated:YES
                     completion:nil];
}

- (UITextField *)getTextFieldWithIndex:(NSInteger)index{
    UITextField * textField = [[UITextField alloc]initWithFrame:CGRectMake(20, 30 + 50 * index, 280, 30) adjustWidth:NO];
    textField.alpha = 0.8;
    textField.textAlignment = NSTextAlignmentLeft;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.text = @[[[CYYNetWorkManager currentUserGet] objectForKey:@"name"],[CYYNetWorkManager currentUserGet].mobilePhoneNumber,@"",@"",@""][index];
    if (index == 0 || index == 1) {
        UILabel * label = [[UILabel alloc]init];
        label.frame = DHFlexibleFrame(CGRectMake(0, 0, 60, 30), NO);
        label.text = @[@"姓名:",@"手机号:"][index];
        textField.leftView = label;
        textField.leftViewMode = UITextFieldViewModeAlways;
    }
    textField.placeholder = @[@"",@"",@"",@"请输入新密码",@"请再次输入新密码"][index];
    textField.inputAccessoryView = [self customKeyboardToolbar];
    return textField;
}

//键盘uitoolbar
- (UIToolbar * )customKeyboardToolbar{
    UIToolbar * toolbar = [[UIToolbar alloc]init];
    toolbar.barTintColor = [UIColor whiteColor];
    toolbar.frame = DHFlexibleFrame(CGRectMake(0, 0, 320, 30), YES);
    //隐藏按钮
    UIBarButtonItem * spaceBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    spaceBarButtonItem.width = 200;
    UIBarButtonItem * rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-bohaojianpanshouqi"] style:UIBarButtonItemStylePlain target:self action:@selector(respondsToDoneButton)];
    rightBarButtonItem.tintColor = [UIColor darkGrayColor];
    toolbar.items = @[spaceBarButtonItem,rightBarButtonItem];
    return toolbar;
}

//判断用户名 字母和汉字
- (BOOL)judgeUsername:(NSString *)string{
    NSString * regularString = @"^[a-zA-Z\u4E00-\u9FA5]+$";
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"self matches %@",regularString];
    //返回值为YES：表明用户名不符合要求
    return ![predicate evaluateWithObject:string];
}



#pragma mark - responds event
- (void)respondsToOKButton:(UIButton *)button{
    button.userInteractionEnabled = NO;//关闭交互
    if (!self.isChangePasswordSwitch.on) {
        //不修改密码
        if ([self.usernameTextField.text isEqualToString:@""]||[self.mobilePhoneNumberTextField.text isEqualToString:@""]) {
            [self alterViewWithMessage:@"用户名或手机号不能为空"];
            button.userInteractionEnabled = YES;
            return;
        }
        if ([self judgeUsername:self.usernameTextField.text]) {
             [self alterViewWithMessage:@"用户名只能是汉字、字母"];
            button.userInteractionEnabled = YES;
            return;
        }
        __weak typeof(self) myVC = self;
        [CYYNetWorkManager updateUserInfoWithNewUsername:myVC.usernameTextField.text newMobilePhoneNumber:myVC.mobilePhoneNumberTextField.text sucess:^(NSString *sucessString) {
//            NSLog(@"%@",sucessString);
            [[ControllerManager sharedManager].rootViewController popViewControllerAnimated:YES];
            [myVC alterViewWithMessage:sucessString];
            button.userInteractionEnabled = YES;
        } fail:^(NSError *error) {
//            NSLog(@"%@",error);
            if (error.code == 301) {
                [myVC alterViewWithMessage:@"输入的手机号有误"];
                button.userInteractionEnabled = YES;
            }else{
                [myVC alterViewWithMessage:@"网络出错"];
                button.userInteractionEnabled = YES;
            }
        }];
    }else if ((![self.newFirstPasswordTextField.text  isEqual: @""]) && (![self.newSecondpasswordTextField.text  isEqual: @""])){
        __weak typeof(self) myVC = self;
        [CYYNetWorkManager updateUserInfoWithNewUsername:myVC.usernameTextField.text newMobilePhoneNumber:myVC.mobilePhoneNumberTextField.text newFirstPassword:myVC.newFirstPasswordTextField.text newSecondPassword:myVC.newSecondpasswordTextField.text sucess:^(NSString *sucessString) {
//            NSLog(@"%@",sucessString);
            [[ControllerManager sharedManager].rootViewController popViewControllerAnimated:YES];
//            [myVC alterViewWithMessage:sucessString];
            _backAlterViewController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:sucessString preferredStyle:UIAlertControllerStyleAlert];
            [_backAlterViewController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                [_backAlterViewController dismissViewControllerAnimated:YES completion:nil];
            }]];
            [myVC.parentViewController presentViewController:_backAlterViewController animated:YES completion:nil];
            button.userInteractionEnabled = YES;
        } fail:^(NSError *error) {
//            NSLog(@"%@",error);
            [myVC alterViewWithMessage:error.domain];
            button.userInteractionEnabled = YES;
        }];
    }else if ([self.newFirstPasswordTextField.text  isEqual: @""] || [self.newSecondpasswordTextField.text  isEqual: @""]){
        [self alterViewWithMessage:@"密码不能为空"];
        button.userInteractionEnabled = YES;
    }
}

- (void)keyboardWillShow:(NSNotification *)notification{
    //获得键盘高度
    //    [(NSValue *)[notification.userInfo objectForKey:@"UIKeyboardBoundsUserInfoKey"] CGRectValue].size.height
    self.mainScrollView.frame = DHFlexibleFrame(CGRectMake(0, 64, 320, 504 - [(NSValue *)[notification.userInfo objectForKey:@"UIKeyboardBoundsUserInfoKey"] CGRectValue].size.height), NO);
    
}

- (void)keyboardWillHiden:(NSNotification *)notification{
    self.mainScrollView.frame = DHFlexibleFrame(CGRectMake(0, 64, 320, 504), NO);
}

//处理键盘隐藏事件
- (void)respondsToDoneButton{
    [self.view endEditing:YES];
}
//修改密码开关
- (void)respondsToSwicth:(UISwitch *)sender{
    self.newFirstPasswordTextField.enabled = sender.on;
    self.newSecondpasswordTextField.enabled = sender.on;
    if (sender.on) {//开
        self.newFirstPasswordTextField.backgroundColor = [UIColor whiteColor];
        self.newSecondpasswordTextField.backgroundColor = [UIColor whiteColor];
    }
    if (!sender.on) {
        self.newFirstPasswordTextField.text = @"";
        self.newSecondpasswordTextField.text = @"";
        self.newFirstPasswordTextField.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];
        self.newSecondpasswordTextField.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];
    }
}

#pragma mark - getter
- (UIScrollView *)mainScrollView{
    if (!_mainScrollView) {
        _mainScrollView = ({
            UIScrollView * scrollView = [[UIScrollView alloc]init];
            scrollView.frame = DHFlexibleFrame(CGRectMake(0, 64, 320, 504), NO);
            scrollView.contentSize = DHFlexibleSize(CGSizeMake(320, 504), NO);
            scrollView.bounces = NO;
            scrollView;
        });
    }
    return _mainScrollView;
}
- (UITextField *)usernameTextField{
    if (!_usernameTextField) {
        _usernameTextField = ({
            [self getTextFieldWithIndex:0];
        });
    }
    return _usernameTextField;
}

-(UITextField *)mobilePhoneNumberTextField{
    if (!_mobilePhoneNumberTextField) {
        _mobilePhoneNumberTextField = ({
            [self getTextFieldWithIndex:1];
        });
    }
    return _mobilePhoneNumberTextField;
}
-(UILabel *)remindLabel{
    if (!_remindLabel) {
        _remindLabel = ({
            UILabel * label = [[UILabel alloc]init];
            label.frame = DHFlexibleFrame(CGRectMake(20, 30 + 50 * 2, 200, 40), NO);
            label.text = @"是否需要修改密码？";
            label;
        });
    }
    return _remindLabel;
}
- (UITextField *)newFirstPasswordTextField{
    if (!_newFirstPasswordTextField) {
        _newFirstPasswordTextField = ({
            [self getTextFieldWithIndex:3];
        });
        _newFirstPasswordTextField.enabled = NO;
        _newFirstPasswordTextField.secureTextEntry = YES;
        _newFirstPasswordTextField.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];
    }
    return _newFirstPasswordTextField;
}
- (UITextField *)newSecondpasswordTextField{
    if (!_newSecondpasswordTextField) {
        _newSecondpasswordTextField = ({
            [self getTextFieldWithIndex:4];
        });
        _newSecondpasswordTextField.enabled = NO;
        _newSecondpasswordTextField.secureTextEntry = YES;
        _newSecondpasswordTextField.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];
    }
    return _newSecondpasswordTextField;
}

-(UIButton *)okButton{
    if (!_okButton) {
        _okButton = ({
            UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = DHFlexibleFrame(CGRectMake(130, 350, 60, 30), NO);
            [button setTitle:@"更新" forState:UIControlStateNormal];
            button.backgroundColor = COLOR_TagBlue;
            [button addTarget:self action:@selector(respondsToOKButton:) forControlEvents:UIControlEventTouchUpInside];
            button;
        });
    }
    return _okButton;
}

- (UISwitch *)isChangePasswordSwitch{
    if (!_isChangePasswordSwitch) {
        _isChangePasswordSwitch = ({
            UISwitch * btnSwitch = [[UISwitch alloc]init];
            btnSwitch.frame = DHFlexibleFrame(CGRectMake(220, 35 + 50 * 2, 80, 40), NO);
            [btnSwitch addTarget:self action:@selector(respondsToSwicth:) forControlEvents:UIControlEventTouchUpInside];
            btnSwitch;
        });
    }
    return _isChangePasswordSwitch;
}
@end
